import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.views import View
from django.http import JsonResponse, HttpResponse
from rest_framework import status
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from Model.models import Package
from radius.models import Radgroupreply as Rad
from tools.Tools import getCurrentUser, createHandleLog, getFileBytes

res = dict()
logger_info = logging.getLogger('info')


class packageView(View):
    res.clear()

    def get(self, request, *args, **kwargs):
        try:
            current = request.GET.get("current")
            pageSize = request.GET.get("pageSize")
            package_name = request.GET.get("package_name")
            dataInfo = Package.objects.all()
            if package_name is not None and package_name != '':
                dataInfo = dataInfo.filter(package_name__contains=package_name)
            total = dataInfo.__len__()
            data = list(dataInfo.values()[int(pageSize) * int(current) - int(pageSize):int(pageSize) * int(current)])
            res['status'] = 200
            res['data'] = data
            res['total'] = total
            res['current'] = current
            res['pageSize'] = pageSize
            res['messages'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        try:
            body = json.loads(request.body)
            package_name = body.get('package_name')
            package_duration = body.get('package_duration')
            package_speed_up = body.get('package_speed_up')
            package_speed_down = body.get('package_speed_down')
            package_price = body.get('package_price')
            state, msg = createPackage(package_name, package_duration, package_speed_up, package_speed_down,
                                       package_price, False)
            if state == 200:
                createHandleLog('新增套餐', str(getCurrentUser(request)), body)
                logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增套餐》权限 新增内容 {body}')
            res['status'] = state
            res['message'] = msg
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def put(self, request, *args, **kwargs):
        try:
            body = json.loads(request.body)
            package_name = body.get('package_name')
            package_duration = body.get('package_duration')
            package_speed_up = body.get('package_speed_up')
            package_speed_down = body.get('package_speed_down')
            package_price = body.get('package_price')
            packageId = body.get('packageId')
            modifyData = Package.objects.get(package_id=packageId)
            modifyData.package_name = package_name
            modifyData.package_duration = package_duration
            modifyData.package_speed_up = package_speed_up
            modifyData.package_speed_down = package_speed_down
            modifyData.package_price = package_price
            Rad.objects.filter(groupname=packageId).delete()
            Rad.objects.create(groupname=modifyData.package_id, attribute='Auth-Type', op=':=', value='Local')
            Rad.objects.create(groupname=modifyData.package_id, attribute='Ascend-Data-Rate', op='=',
                               value=str(int(modifyData.package_speed_up) * 1000000))
            Rad.objects.create(groupname=modifyData.package_id, attribute='Ascend-Xmit-Rate', op='=',
                               value=str(int(modifyData.package_speed_down) * 1000000))
            Rad.objects.create(groupname=modifyData.package_id, attribute='Huawei-Input-Average-Rate', op='=',
                               value=str(int(modifyData.package_speed_up) * 1000000))
            Rad.objects.create(groupname=modifyData.package_id, attribute='Huawei-Output-Average-Rate', op='=',
                               value=str(int(modifyData.package_speed_down) * 1000000))
            modifyData.save()
            createHandleLog('修改套餐', str(getCurrentUser(request)), body)
            logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改套餐》权限 修改内容 {body}')
            res['status'] = 200
            res['message'] = '套餐修改成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def delete(self, request, *args, **kwargs):
        try:
            packageId = request.GET.get("packageId")
            delPackage = Package.objects.get(package_id=packageId)
            Rad.objects.filter(groupname=packageId).delete()
            delPackage.delete()
            res['status'] = 200
            res['message'] = '套餐删除成功'
            createHandleLog('删除套餐', str(getCurrentUser(request)), delPackage.package_name)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除客户》权限 删除内容 {delPackage.package_name}')
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


def getDuration(request):
    """
    查询套餐周期
    """
    res.clear()
    try:
        if request.method == 'GET':
            dataInfo = list(Package.objects.all().values('package_duration').order_by('package_duration').distinct())
            res['status'] = 200
            res['data'] = dataInfo
            res['message'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


def getPackage(request):
    """
    根据周期查询套餐
    """
    res.clear()
    try:

        if request.method == "GET":
            package_duration = request.GET.get("package_duration")
            dataInfo = list(
                Package.objects.filter(package_duration=package_duration).values('package_id', 'package_name',
                                                                                 'package_price'))
            res['status'] = 200
            res['data'] = dataInfo
            res['message'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


def UploadPackage(request):
    res.clear()
    try:
        if request.method == "POST":
            body = json.loads(request.body)
            upload_data = body.get('list')
            """{'套餐名称': '100M ', '套餐周期': 6, '套餐上行': 10, '套餐下行': 100, '套餐金额': 200}"""
            for data in upload_data:
                name, duraction, up, down, money = data.values()
                print(name, duraction, up, down, money)
                createPackage(name, duraction, up, down, money, True)
            res['status'] = 200
            res['message'] = "上传成功"
            return JsonResponse(res, status=HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


@transaction.atomic
def createPackage(name, duraction, up, down, money, loop=False):
    """
    :param name 套餐名称
    :param duraction 套餐周期
    :param up 套餐上行
    :param down 套餐下行
    :param money 套餐金额
    :param loop 是否循环
    """
    try:
        # 套餐上下行为整数
        try:
            duraction = float(duraction)
            up = int(up)
            down = int(down)
        except:
            return 400, '套餐周期,套餐上行,套餐下行须为整数'
        if not loop:
            if not Package.objects.filter(package_name__contains=name, package_duration=duraction).exists():
                createDate = Package.objects.create()
                createDate.package_id = createDate.id
                createDate.package_name = name
                createDate.package_duration = duraction
                createDate.package_speed_up = up
                createDate.package_speed_down = down
                createDate.package_price = money
                Rad.objects.create(groupname=createDate.package_id, attribute='Auth-Type', op=':=', value='Local')
                Rad.objects.create(groupname=createDate.package_id, attribute='Ascend-Data-Rate', op='=',
                                   value=str(int(createDate.package_speed_up) * 1000000))
                Rad.objects.create(groupname=createDate.package_id, attribute='Ascend-Xmit-Rate', op='=',
                                   value=str(int(createDate.package_speed_down) * 1000000))
                Rad.objects.create(groupname=createDate.package_id, attribute='Huawei-Input-Average-Rate', op='=',
                                   value=str(int(createDate.package_speed_up) * 1000000))
                Rad.objects.create(groupname=createDate.package_id, attribute='Huawei-Output-Average-Rate', op='=',
                                   value=str(int(createDate.package_speed_down) * 1000000))
                createDate.save()
                return 200, '添加成功'
            else:
                return 400, '不能增加已有套餐'
        else:
            if not Package.objects.filter(package_name__contains=name, package_duration=duraction).exists():
                createDate = Package.objects.create()
                createDate.package_id = createDate.id
                createDate.package_name = name
                createDate.package_duration = duraction
                createDate.package_speed_up = up
                createDate.package_speed_down = down
                createDate.package_price = money
                Rad.objects.create(groupname=createDate.package_id, attribute='Auth-Type', op=':=', value='Local')
                Rad.objects.create(groupname=createDate.package_id, attribute='Ascend-Data-Rate', op='=',
                                   value=str(int(createDate.package_speed_up) * 1000000))
                Rad.objects.create(groupname=createDate.package_id, attribute='Ascend-Xmit-Rate', op='=',
                                   value=str(int(createDate.package_speed_down) * 1000000))
                Rad.objects.create(groupname=createDate.package_id, attribute='Huawei-Input-Average-Rate', op='=',
                                   value=str(int(createDate.package_speed_up) * 1000000))
                Rad.objects.create(groupname=createDate.package_id, attribute='Huawei-Output-Average-Rate', op='=',
                                   value=str(int(createDate.package_speed_down) * 1000000))
                createDate.save()
            else:
                pass

    except:
        pass


def DownloadPackage(request):
    res.clear()
    try:
        if request.method == 'GET':
            out_stream = getFileBytes('tc.xls')
            response = HttpResponse(content_type='application/vnd.ms-excel', charset="UTF-8")
            response.write(out_stream)
            return response
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)
